package com.zmn.oms.task.listener;

import com.alibaba.fastjson.JSON;
import com.zmn.base.common.data.common.dro.company.CompanyDRO;
import com.zmn.base.common.data.dubbo.interfaces.company.CompanyListRemoteService;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.manager.mq.annotation.AliyunMQListener;
import com.zmn.oms.business.interfaces.work.tag.OrderTagBService;
import com.zmn.oms.common.dto.QueueOrderNodeNotifyDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.datasync.ElasticSearchDataSyncService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLTransientConnectionException;
import java.util.Objects;

/**
 * 类描述：同步支付凭证
 *
 * @author wangxiaokun
 * @since 2021/05/10 17:23
 */
@AliyunMQListener(topic = "${spring.mq.topic.oms}")
@Component
@Slf4j
@Deprecated
public class OrderPayChangeListener {

    @Autowired
    private OrderWorkService orderWorkService;

    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    CompanyListRemoteService companyListRemoteService;

    @Autowired
    private ElasticSearchDataSyncService elasticSearchDataSyncService;

    @Autowired
    private OrderTagBService orderTagBService;

    /**
     * 订单完成操作
     * @param message
     * @see com.zmn.oms.task.listener.OrderWorkNodeListener#orderComplete
     */
    //@AliyunMQHandler(tags = MessageQueueTagConsts.ORDER_COMPLETE)
    public void orderCompleteChange(String message){
        log.debug("#orderpay#complete#change# message:[{}]", message);
        try {
            QueueOrderNodeNotifyDTO dto = JSON.parseObject(message, QueueOrderNodeNotifyDTO.class);
            if (Objects.isNull(dto)){
                return;
            }
            // 补偿子公司
            this.compensatesOrderWorkCompany(dto.getOrderId(), dto.getWorkId());

            elasticSearchDataSyncService.syncPayIndex(dto.getOrderId());
        } catch (Exception e) {
            log.error("#oms#orderpaychange#重建索引消费失败 {}", e.getMessage(), e);
            if (e instanceof SQLTransientConnectionException) {
                log.error("数据库连接错误");
            }
        }
    }

    /**
     * 补偿缺失的订单子公司数据
     * @param orderId
     * @param workId
     */
    private void compensatesOrderWorkCompany(Long orderId,Long workId) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (NumberUtil.isNotNullOrZero(orderWork.getCompanyId())) {
            return;
        }

        log.info("[{}]订单完成---无子公司数据", orderId);
        if (NumberUtil.isNullOrZero(orderWork.getManageCompanyId())) {
            log.error("[{}]订单完成---无服务公司数据", orderId);
            return;
        }

        CompanyDRO companyDRO = companyListRemoteService.getCompanyDROById(orderWork.getManageCompanyId()).getData();
        log.info("baseCompanyListRemoteService#getCompanyByCompanyId[{}]出参[{}]", orderWork.getManageCompanyId(), JSON.toJSONString(companyDRO));
        if (Objects.isNull(companyDRO)) {
            return;
        }
        log.info("[{}]订单完成--补偿子公司数据", orderId);
        OrderWork upOrderWork = new OrderWork();
        upOrderWork.setOrderId(orderId);
        upOrderWork.setWorkId(workId);
        upOrderWork.setCompanyId(companyDRO.getSubCompanyId());
        upOrderWork.setCompanyName(companyDRO.getSubCompanyName());
        orderWorkService.updateOrderWorkCompany(upOrderWork);
    }

    /**
     * 订单收单操作
     * @param message
     * @see com.zmn.oms.task.listener.OrderWorkNodeListener#orderCheckout
     */
    //@AliyunMQHandler(tags = MessageQueueTagConsts.ORDER_CHECKOUT)
    public void orderCheckoutChange(String message){
        log.debug("#orderpay#checkout#change# message:[{}]", message);
        try {
            QueueOrderNodeNotifyDTO dto = JSON.parseObject(message, QueueOrderNodeNotifyDTO.class);
            if (Objects.isNull(dto)){
                return;
            }
            elasticSearchDataSyncService.syncPayIndex(dto.getOrderId());
        } catch (Exception e) {
            log.error("#oms#orderpaychange#重建索引消费失败 {}", e.getMessage(), e);
            if (e instanceof SQLTransientConnectionException) {
                log.error("数据库连接错误");
            }
        }
    }

    /**
     * 订单算账操作
     * @param message
     * @see com.zmn.oms.task.listener.OrderWorkNodeListener#orderAccount
     */
    //@AliyunMQHandler(tags = MessageQueueTagConsts.ORDER_ACCOUNT)
    public void orderAccountChange(String message){
        log.debug("#orderpay#checkout#change# message:[{}]", message);
        try {
            QueueOrderNodeNotifyDTO dto = JSON.parseObject(message, QueueOrderNodeNotifyDTO.class);
            if (Objects.isNull(dto)){
                return;
            }
            elasticSearchDataSyncService.syncPayIndex(dto.getOrderId());
        } catch (Exception e) {
            log.error("#oms#orderpaychange#重建索引消费失败 {}", e.getMessage(), e);
            if (e instanceof SQLTransientConnectionException) {
                log.error("数据库连接错误");
            }
        }
    }

    // /**
    //  * 工单支付凭证同步ES监听
    //  * @param message
    //  */
    // @AliyunMQHandler(tags = OmsMqTagConsts.ZMN_TOPIC_OMS_ORDER_PAY_CHANGE_TAG)
    // public void orderPayChange(String message){
    //     List<Long> orderIdList = null;
    //     try {
    //         orderIdList = JSON.parseArray(message, Long.class);
    //         if (orderIdList.size() > 300) {
    //             log.info("#mq#orderpaychange#2es#start");
    //         } else {
    //             log.debug("#mq#orderpaychange#2es#start");
    //         }
    //         syncEsOrderPayBService.sync(orderIdList);
    //         if (orderIdList.size() > 300) {
    //             log.info("#mq#orderpaychange#2es#end orderIdList.count:{}", orderIdList.size());
    //         } else {
    //             log.debug("#mq#orderpaychange#2es#end orderIdList.count:{}", orderIdList.size());
    //         }
    //     } catch (Exception e) {
    //         log.error("#oms#orderpaychange#重建索引消费失败 {}", e.getMessage(), e);
    //         log.error("#oms#orderpaychange#未同步工单列表[{}]", orderIdList);
    //         if (e instanceof SQLTransientConnectionException) {
    //             log.error("数据库连接错误");
    //         }
    //     }
    // }
}
